package com.qfedu.video.controller;

import com.qfedu.video.entry.User;
import com.qfedu.video.redis.JedisClientPool;
import com.qfedu.video.service.UserService;
import com.qfedu.video.utils.ImageCut;
import com.qfedu.video.utils.Md5Utils;
import com.qfedu.video.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;

/**
 * @author yanzhenwei
 * @date 2021-07-13 15:47
 * 专门处理前端的用户的请求
 *    登录
 *    注册
 *    忘记密码
 *    修改密码
 *    修改个人信息
 *    上传头像
 *    退出登录
 */
@Controller

@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Value("${upload.dir}")
    String dir;

    @Value("${upload.url}")
    String url;


    @Autowired
    JedisClientPool jedisClientPool;



    @RequestMapping("/insertUser")
    @ResponseBody
    public String register(User user){

        user.setPassword(Md5Utils.md5(user.getPassword()));
        userService.register(user);
        return "success";
    }

    @RequestMapping("/loginUser")
    @ResponseBody
    public String login(User user, HttpSession session){

        user.setPassword(Md5Utils.md5(user.getPassword()));
        boolean result  =userService.login(user);
        //登录成功以后要在session中保存邮箱信息
        if(result){
            session.setAttribute("email",user.getEmail());
        }
        return result?"success":"fail";
    }

    @ResponseBody
    @RequestMapping("/validateEmail")
    public String validateEmail(String email){


        boolean result = userService.validateEmail(email);
        return result ? "fail" :"success";
    }

    @RequestMapping("/showMyProfile")
    public String showMyProfile(HttpSession session, Model model){

        String email =(String)session.getAttribute("email");
        User user =userService.getUserByEmail(email);
        model.addAttribute("user",user);
        return "before/my_profile";
    }

    @RequestMapping("/changeAvatar")
    public String changeAvatar(HttpSession session, Model model){

        //String email =(String)session.getAttribute("email");
        //User user =userService.getUserByEmail(email);
        //model.addAttribute("user",user);
        return "before/change_avatar";
    }

    /**
     *  页面： 1、多段式表单  2 post请求 3、type=file
     *  准备：导入两个工具包
     *  springmvc  需要编写文件上传解析器
     *
     *
     */
    @RequestMapping("/upLoadImage")
    public String upLoadImage(HttpServletRequest request,MultipartFile image_file,HttpSession session) throws Exception{

        String x1 = request.getParameter("x1");
        String x2 = request.getParameter("x2");
        String y1 = request.getParameter("y1");
        String y2 = request.getParameter("y2");

        float xx1 = Float.parseFloat(x1);
        float xx2 = Float.parseFloat(x2);
        float yy1 = Float.parseFloat(y1);
        float yy2 = Float.parseFloat(y2);

        System.out.println(x1);

        int x=0,y=0,width=0,height=0;
        width  = (int) (xx2 -xx1);
        height  = (int) (yy2 -yy1);




        String originalFilename = image_file.getOriginalFilename();
        int dotIndex = originalFilename.lastIndexOf(".");
        String suffix  = originalFilename.substring(dotIndex);
        String newName= UUIDUtils.getStr() + suffix;
        System.out.println(newName);

        String imagePath = dir+newName;
        File file = new File(imagePath);
        image_file.transferTo(file);

        ImageCut imageCut=new ImageCut();
        imageCut.cutImage(imagePath,(int)xx1,(int)yy1,width,height);


        String email=(String)session.getAttribute("email");

        User user =new User();
        user.setEmail(email);
        user.setImgUrl(url+newName);

        System.out.println(url);
        System.out.println(dir);
        //更新数据
        userService.updateImgUrlByEmail(user);

        return "redirect:/user/showMyProfile";
    }


    @RequestMapping("/changeProfile")
    public String changeProfile(HttpSession session,Model model){

        String email =(String)session.getAttribute("email");
        User user =userService.getUserByEmail(email);
        model.addAttribute("user",user);

        return "before/change_profile";
    }


    @RequestMapping("/updateUser")
    public String updateUser(User user){


        userService.updateUserById(user);

        return "redirect:/user/showMyProfile";
    }

    @RequestMapping("/forgetPassword")
    public String forgetPassword(){
        return "before/forget_password";
    }

    @RequestMapping("/sendEmail")
    @ResponseBody
    public String sendEmail(String email){
        //调用service发送邮件
       String validateCode=  userService.sendEmail(email);

       jedisClientPool.set("validateCode:"+email,validateCode);
       jedisClientPool.expire("validateCode:"+email,60);

        return "success";
    }

    @RequestMapping("/validateEmailCode")
    public String validateEmailCode(String email,String code){

        String validateCode = jedisClientPool.get("validateCode:" + email);

        if(code.equals(validateCode)){
            //说明正确
            //可以跳转到修改密码的界面
            return "before/reset_password";
        }
        return "redirect:/user/forgetPassword";
    }




}
